package me.xplabs.engine.time 
{
	import me.xplabs.constant.TimeVars;
	/**
	 * ...
	 * @author xiaohan
	 */
	public class TimeUpdateNode 
	{
		public var key:int;
		private var _obj:Object;
		private var _pars:Object;
		private var _spars:Object;
		private var _updateFunc:Function;
		private var _endFunc:Function;
		private var _duration:int;
		private var _curTime:int;
		public function TimeUpdateNode(pkey:int, ppars:Object, pduration:Number = -1, pobj:Object = null)
		{
			key = pkey;
			if (pduration == -1) _duration = -1;
			else _duration = int(pduration * 1000);
			_curTime = 0;
			
			if (ppars[TimeVars.update]) {
				_updateFunc = ppars[TimeVars.update];
				delete ppars[TimeVars.update];
			}
			if (ppars[TimeVars.complete]) {
				_endFunc = ppars[TimeVars.complete];
				delete ppars[TimeVars.complete];
			}
			
			if(pobj!=null)
			{
				_obj = pobj;
				_pars = ppars;
				_spars = new Object();
				var parName:String;
				for (parName in ppars) 
				{
					if (_obj[parName] == null) delete ppars[parName]; 
					else _spars[parName] = _obj[parName];
				}
			}
		}
		
		public function update(gap:int):Boolean
		{
			if (_duration == -1) {
				
				if (_updateFunc != null)
				{
					if (_updateFunc.length == 0) _updateFunc();
					else _updateFunc(gap);
				}
				return false;
			}
			if (_updateFunc != null)
			{
				if (_updateFunc.length == 0) _updateFunc();
				else _updateFunc(gap);
			}
			
			_curTime += gap;
			var parName:String;
			if (_curTime >= _duration) {
				if (_pars != null)
				{
					for (parName in _pars) 
						_obj[parName] = _pars[parName];
				}
				if (_endFunc != null) _endFunc(key);
				return true;
			}
			if (_pars != null)
			{
				for (parName in _pars) 
					_obj[parName] = _spars[parName] + (_pars[parName] - _spars[parName]) * _curTime / _duration;
			}
			return false;
		}
	}
}